#include "utils.h"
#include <QCryptographicHash>
#include <QFile>
#include <QStringList>

QString Utils::escape(QString str, QString separator, QString delim)
{
    str = str.replace(ESCAPE,DOUBLE_ESCAPE);
    if(!separator.isEmpty()) str = str.replace(separator,separator+ESCAPE);
    if(!delim.isEmpty()) str = str.replace(delim,delim+ESCAPE);

    return str;
}

QString Utils::unescape(QString str, QString separator, QString delim)
{
    str = str.replace(DOUBLE_ESCAPE,ESCAPE);
    if(!separator.isEmpty()) str = str.replace(separator+ESCAPE,separator);
    if(!delim.isEmpty()) str = str.replace(delim+ESCAPE,delim);

    return str;
}

int Utils::findSeparator(QString str, QString sep, QString escape, int from)
{
    int i;

    for(i=from; i<str.length(); i++) {
        if(str.indexOf(escape,i)==i) {
            i++;
            continue;
        }
        if(str.indexOf(sep,i)==i) {
            return i;
        }
    }

    return -1;
}

QStringList Utils::mySplit(QString str, QString sep, QString escape)
{
    int begin = 0;
    int pos = findSeparator(str,sep,escape,0);
    QStringList result;

    while(pos!=-1) {
        if(pos==begin) result.append("");
        else result.append(str.mid(begin,pos-begin));
        begin = pos+sep.length();
        pos = findSeparator(str,sep,escape,begin);
    }

    if(begin<=str.length()) result.append(str.mid(begin));
    return result;
}

QString Utils::jPair(QString key, QString value)
{
    return "\""+key+"\":"+"\""+value+"\"";
}

QString Utils::jPair(QString key, qint32 value)
{
    return "\""+key+"\":"+QString::number(value);
}

QString Utils::jPair(QString key, qreal value)
{
    return "\""+key+"\":"+QString::number(value);
}

QString Utils::jPair(QString key, qulonglong value)
{
    return "\""+key+"\":"+QString::number(value);
}

QString Utils::StringMD5(QString str)
{
    return QCryptographicHash::hash(str.toUtf8(),QCryptographicHash::Md5);
}

QString Utils::FileMD5(QString fname)
{
    QCryptographicHash hash(QCryptographicHash::Md5);

    QFile file(fname);

    if(file.open(QIODevice::ReadOnly)) {
        hash.addData(&file);
    }

    QString base64StringHash(hash.result().toBase64());

    return base64StringHash;
}

bool Utils::saveData(const QByteArray &data, QString fname)
{
    QFile file(fname);

    if(!file.open(QIODevice::WriteOnly)) {
        return false;
    }

    if(file.write(data)==-1) {
        return false;
    }

    file.close();

    return true;
}

